package Loginc

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"io"
	"log"
	"net/http"
	"xiezhi/app/Middleware/Jwtc"
	"xiezhi/database/jsdb"
)

type ReqUserInfo struct {
	Username string `json:"username"`
	Password string `json:"password"`
}

func Login(c *gin.Context) {
	// username := c.Query("username")
	// password := c.Query("password")
	reqBody, _ := io.ReadAll(c.Request.Body)
	// log.Println("method", c.Request.Method)
	// log.Println("body", string(reqBody))
	// log.Println("clientIP", c.Request.RemoteAddr)
	// log.Println("url", c.Request.RequestURI)
	var m ReqUserInfo
	err := json.Unmarshal(reqBody, &m) // 反序列化
	if err != nil {
		log.Println(err)
	}

	// 新用户存储到json文件中
	_, tag, user := jsdb.GetReadUserData(m.Username, m.Password)
	if tag {
		// log.Printf("%v", userData)
		sign, err := Jwtc.Sign(user.Username)
		if err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{
				"error": err.Error(),
			})
		}
		c.JSON(http.StatusOK, gin.H{
			"access_token": sign,
		})
	} else {
		c.JSON(404, gin.H{
			"message": "用户不存在",
		})
	}

}

func Register(c *gin.Context) {
	reqBody, _ := io.ReadAll(c.Request.Body)
	var m ReqUserInfo
	err := json.Unmarshal(reqBody, &m) // 反序列化
	if err != nil {
		log.Println(err)
	}

	// 新用户存储到json文件中
	userData := jsdb.GetWriteUserData(m.Username, m.Password)
	c.JSON(http.StatusOK, gin.H{
		"message": "注册用户成功",
		"data":    userData,
	})
}
